//
//  HomeViewController.m
//  HealthFamily
//
//  Created by 吴欧 on 2020/9/28.
//  Copyright © 2020 吴欧. All rights reserved.
//

#import "HomeViewController.h"
#import "HEMoreView.h"
#import "HEAssesListView.h"
#import "ChangeFontManager.h"

#import "HEMissonListView.h"
#import "HEVideoListView.h"
#import "HEViewController.h"

#import "XYTransitionProtocol.h"
#import "HEFindDoctorViewController.h"
#import "HEFreeConsulViewController.h"

#import "HEReportReadViewController.h"
#import "HENurseViewController.h"
#import "HERecoverViewController.h"
#import "HEOrgMapViewController.h"


#import "HEHomeFromModel.h"
#import "HEDocImInfoView.h"
#import "HEIMInfoEntity.h"
#import "HEWeatherModel.h"
#import "HESelectCityViewController.h"

#import "JFCSTableViewController.h"
#import "JFCSConfiguration.h"
#import "JFCSDataOpreation.h"
#import "HEMySignViewController.h"
#import "ZFScanViewController.h"
#import "ZQSearchViewController.h"
#import "HESearchData.h"
#import "HEHealthManageViewController.h"
#import "HEHealthCheckDataController.h"
#import "HEAIAudioView.h"

#import "HECheckPictureViewController.h"
#import "HEFindTeamViewController.h"

@interface HomeViewController ()<UITableViewDelegate, UITableViewDataSource, QMUITextFieldDelegate, XYTransitionProtocol, BMKLocationManagerDelegate, JFCSTableViewControllerDelegate, HESocketManagerDelegate, CLLocationManagerDelegate>

@property (nonatomic, strong) GDTableView *tableView;
@property (nonatomic, strong) HEHomeFromModel *formModel;
@property (nonatomic, strong) NSMutableArray *sections;

@property(nonatomic, strong) UIView *nav;
@property(nonatomic, strong) UIScrollView *scrollViews;


@property (nonatomic, strong) UIView *itemContent;
@property (nonatomic, strong) NSString *drugsUrl;
@property (nonatomic, assign) BOOL isHasPrivate;
@property (nonatomic, strong) HEDocImInfoView *imInfoView;
@property (nonatomic, strong) UIView *serWarp;
@property (nonatomic, strong) UIScrollView *mainScrollView;
@property (nonatomic, strong) UIImageView *banner;

@property (nonatomic, strong) HEDoctorInfoModel *privateModel;

@property (nonatomic, strong) HEWeatherModel *weatherInfo;
@property (nonatomic, strong) UILabel *cityLb;
@property (nonatomic, strong) UILabel *weatherLb;


@property (nonatomic, strong) BMKLocationManager *locationManager; //定位对象
@property (nonatomic, strong) BMKLocation *courrentLoc;
@property (nonatomic, strong) NSString *selectCity;
@property (nonatomic, strong) HESearchData *searchData;

@property (nonatomic, strong) CLLocationManager *sysLocManager;

@property (nonatomic, strong) HEAssesListView *assList;
@property (nonatomic, strong) HEMissonListView *missonList;
@property (nonatomic, strong) HEVideoListView *videoList;

@end

@implementation HomeViewController

- (HEHomeFromModel *)formModel {
    if (!_formModel) {
        _formModel = [[HEHomeFromModel alloc] init];
        _formModel.proxyVC = self;
    }
    return _formModel;
}

-(void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    if (_scrollViews) {
     for (UIView *btn in _scrollViews.subviews) {
         [btn layoutSubviews];
     }
    }
    
    [_itemContent layoutSubviews];
    
    [self loadUserPrivateData];
}
 
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
     
    self.isHidenNaviBar = YES;

    [self requestWhenInUseAuthorization];

    [self initUI];
    
    [self refreshWeatherData];
    
    [[HESocketManager sharedManager] addDelegate:self];
    
    [self getHasRead];
}
 

- (void)initUI {
    
    CGFloat offestH = kStatusBarHeight - 20;

    _nav = [UIView new];
    _nav.backgroundColor = [UIColor colorWithHexString:@"#F8F8F8"];
    [self.view addSubview:_nav];
    
    UIImageView *backView = [UIImageView new];
    [_nav addSubview:backView];
    backView.userInteractionEnabled = YES;
    backView.image = IMAGE_NAMED(@"home_title");
    
    // city
    UIView *weatherWarp = [UIView new];
    [backView addSubview:weatherWarp];
    UILabel *cityLb = [UILabel new];
    cityLb.text = @"定位中...";
    cityLb.textColor = KWhiteColor;
    cityLb.font = DYBlodFont(16);
    _cityLb = cityLb;
    [weatherWarp addSubview: cityLb];
    
    UITapGestureRecognizer *cityTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(selectCityClick)];
    [weatherWarp addGestureRecognizer:cityTap];
    UIImageView *arrow = [[UIImageView alloc] initWithImage:IMAGE_NAMED(@"arrow_down")];
    [weatherWarp addSubview: arrow];
    
    // logo
    UILabel *weatherLb = [UILabel new];
    weatherLb.text = @"";
    weatherLb.textColor = KWhiteColor;
    weatherLb.font = DYBlodFont(16);
    _weatherLb = weatherLb;
    [backView addSubview: weatherLb];
    
    // 扫一扫
    UIImageView *scan = [[UIImageView alloc] initWithImage:IMAGE_NAMED(@"home_scan")];
    scan.frame = CGRectMake(KScreenWidth - 23 - 15, 18.5 + kStatusBarHeight, 23, 23);
    [backView addSubview:scan];
    scan.userInteractionEnabled = YES;
    UITapGestureRecognizer *scanTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(scanClick)];
    [scan addGestureRecognizer:scanTap];
    
    [weatherWarp mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(scan);
        make.left.equalTo(backView).offset(20);
    }];
    
    [cityLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weatherWarp);
        make.left.equalTo(weatherWarp).offset(0);
        make.bottom.equalTo(weatherWarp);
    }];
    
    [arrow mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(cityLb);
        make.left.equalTo(cityLb.mas_right).offset(3);
        make.right.equalTo(weatherWarp);
    }];
    
    [weatherLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(scan);
        make.left.equalTo(arrow.mas_right).offset(8);
    }];
    
    // 输入框
    QMUITextField *searchTF = [QMUITextField new];
    [_nav addSubview:searchTF];
    searchTF.backgroundColor = [UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:1.0];
    searchTF.layer.shadowColor = [UIColor colorWithRed:13/255.0 green:98/255.0 blue:218/255.0 alpha:0.08].CGColor;
    searchTF.layer.shadowOffset = CGSizeMake(0,5);
    searchTF.layer.shadowOpacity = 1;
    searchTF.layer.shadowRadius = 6;
    searchTF.layer.cornerRadius = 22;
    searchTF.font = DYFont(16);
    
    searchTF.placeholder = @"搜疾病、视频、资讯";
    searchTF.userInteractionEnabled = YES;
    searchTF.placeholderColor = [UIColor colorWithHexString:@"#AAAAAA"];
    searchTF.delegate = self;
    
    UIView *leftWarp = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 49, 18)];
    UIImageView *leftIcon = [[UIImageView alloc] initWithImage:IMAGE_NAMED(@"home_search")];
    leftIcon.frame = CGRectMake(20, 0, 18, 18);
    [leftWarp addSubview:leftIcon];
    searchTF.leftViewMode = UITextFieldViewModeAlways;
    searchTF.leftView = leftWarp;
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(searchClickhandler)];
    [searchTF addGestureRecognizer:tap];
         
    _nav.sd_layout
    .topEqualToView(self.view)
    .rightEqualToView(self.view)
    .leftEqualToView(self.view)
    .heightIs(130 + offestH);
    
    backView.sd_layout
    .topEqualToView(_nav)
    .rightEqualToView(_nav)
    .leftEqualToView(_nav)
    .heightIs(97 + offestH);
    
    searchTF.sd_layout
    .topSpaceToView(_nav, 76 + offestH)
    .centerXEqualToView(_nav)
    .rightSpaceToView(_nav, 15)
    .leftSpaceToView(_nav, 15)
    .heightIs(44);
    [self.view bringSubviewToFront:_nav];

    [self initScrollView];
}

- (void)initScrollView {
    UIScrollView *scrollView = [[UIScrollView alloc] init];
    scrollView.scrollEnabled = YES;
    scrollView.backgroundColor = [UIColor colorWithHexString:@"#F8F8F8"];
     [self.view addSubview:scrollView];
    _mainScrollView = scrollView;
        
    // 添加下拉刷新控件
    KWeakSelf
    scrollView.mj_header= [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self refreshWeatherData];

        [self setupWetherData];
        [weakSelf.assList loadData];
        [weakSelf.missonList loadData];
        [weakSelf.videoList loadData];
     }];
    
    // 私人医生
    UIImageView *banner = [[UIImageView alloc] initWithImage:IMAGE_NAMED(@"home_banner")];
    banner.contentMode = UIViewContentModeScaleAspectFill;
    _banner = banner;
    banner.layer.cornerRadius = 10;
    banner.layer.masksToBounds = YES;
    banner.clipsToBounds = YES;
    [scrollView addSubview:banner];
    
    UITapGestureRecognizer *bannerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(bannerTapClick)];
    [banner addGestureRecognizer:bannerTap];
    
 
    // 资讯、找医生
    UIView *serWarp = [UIView new];
    _serWarp = serWarp;
    [scrollView addSubview:serWarp];
    
    NSArray *serList = @[@"home_ai_service", @"home_find_doctor"];
    NSMutableArray *serArr = [NSMutableArray array];
    int i = 1;
    for (NSString *img in serList) {
        UIImageView *aiService = [[UIImageView alloc] initWithImage:IMAGE_NAMED(img)];
        aiService.contentMode = UIViewContentModeScaleAspectFill;
        aiService.tag = i;
        aiService.userInteractionEnabled = YES;
        aiService.layer.cornerRadius = 10;
        aiService.layer.masksToBounds = YES;
        aiService.clipsToBounds = YES;
        [serWarp addSubview:aiService];
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(serverClick:)];
        [aiService addGestureRecognizer:tap];
        
        aiService.sd_layout
        .heightIs(80);
        [serArr addObject:aiService];
        i++;
    }
    
    scrollView.sd_layout
    .topSpaceToView(_nav, 0)
    .rightEqualToView(self.view)
    .leftEqualToView(self.view)
    .bottomSpaceToView(self.view, 0);
    
    banner.sd_layout
    .topSpaceToView(scrollView, 5)
    .leftSpaceToView(scrollView, 15)
    .rightSpaceToView(scrollView, 15)
    .heightIs(80);
     
    serWarp.sd_layout
    .topSpaceToView(banner, 15)
    .leftSpaceToView(scrollView, 0)
    .rightSpaceToView(scrollView, 0)
    .heightIs(80);
    
    [serWarp setupAutoWidthFlowItems:serArr withPerRowItemsCount:2 verticalMargin:15 horizontalMargin:15 verticalEdgeInset:0 horizontalEdgeInset:15];
    
    
    // 服务选项宫格
    // 资讯、找医生
    UIView *itemWarp = [UIView new];
    [scrollView addSubview:itemWarp];

    NSArray *itemImgList = @[
                             @{@"name":@"护理上门", @"icon":@"home_nurse_home"},
                             @{@"name":@"康复上门", @"icon":@"home_jk_health"}
    ];
    NSMutableArray *itemArr = [NSMutableArray array];
    int j = 0;
    for (NSDictionary *img in itemImgList) {
        
        QMUIButton *btn = [[QMUIButton alloc] init];
        btn.imagePosition = QMUIButtonImagePositionTop;// 将图片位置改为在文字下方
        [btn setTitleColor:CNavBgColor forState:UIControlStateNormal];
        btn.imageEdgeInsets = UIEdgeInsetsMake(-10, 0, 0, 0);
        btn.backgroundColor = KHexColor(@"E9F1FD");
        [btn setImage:UIImageMake(img[@"icon"]) forState:UIControlStateNormal];
        [btn setTitle:img[@"name"] forState:UIControlStateNormal];
        btn.titleLabel.font = DYBlodFont(15);
        btn.tag = j;
        [itemWarp addSubview:btn];
        [btn addTarget:self action:@selector(itemServerClick:) forControlEvents:UIControlEventTouchUpInside];
        btn.layer.cornerRadius = 10;
        btn.layer.masksToBounds = YES;
        
        btn.sd_layout
        .heightIs(80);
        [itemArr addObject:btn];
        j++;
    }
    
    itemWarp.sd_layout
    .topSpaceToView(serWarp, 15)
    .leftSpaceToView(scrollView, 0)
    .rightSpaceToView(scrollView, 0)
    .heightIs(80);

    [itemWarp setupAutoWidthFlowItems:itemArr withPerRowItemsCount:2 verticalMargin:15 horizontalMargin:15 verticalEdgeInset:0 horizontalEdgeInset:15];
    
    
    //******  健康管理
    UIView *healthManage = [[UIView alloc] init];
    healthManage.backgroundColor = [UIColor whiteColor];
    healthManage.layer.shadowColor = [UIColor colorWithRed:13/255.0 green:98/255.0 blue:218/255.0 alpha:0.08].CGColor;
    healthManage.layer.shadowOffset = CGSizeMake(0,5);
    healthManage.layer.shadowOpacity = 1;
    healthManage.layer.shadowRadius = 6;
    healthManage.layer.cornerRadius = 10;
    [scrollView addSubview:healthManage];
    
    healthManage.sd_layout
    .topSpaceToView(itemWarp, 15)
    .leftSpaceToView(scrollView, 15)
    .rightSpaceToView(scrollView, 15)
    .heightIs(122);

    
    // 健康管理
    HEMoreView *allView = [[HEMoreView alloc] init];
    allView.title = @"健康管理";
    [healthManage addSubview:allView];
    UITapGestureRecognizer *healthMngTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toHealthMangeClick)];
    [allView addGestureRecognizer:healthMngTap];
    
    allView.sd_layout
    .topSpaceToView(healthManage, 13)
    .rightSpaceToView(healthManage, 15)
    .leftSpaceToView(healthManage, 15)
    .heightIs(20);
 
    
    UIScrollView *manContent = [[UIScrollView alloc] init];
    manContent.scrollEnabled = YES;
    manContent.showsVerticalScrollIndicator = NO;
    manContent.showsHorizontalScrollIndicator = NO;
    [healthManage addSubview:manContent];
    _scrollViews = manContent;
    
    manContent.sd_layout
    .topSpaceToView(allView, 15)
    .rightSpaceToView(healthManage, 5)
    .leftSpaceToView(healthManage, 5)
    .bottomSpaceToView(healthManage, 0);
    
    NSArray *manImgList = @[@{@"name":@"身高", @"icon":@"home_tall"},
                             @{@"name":@"体重", @"icon":@"home_weight"},
                             @{@"name":@"体温", @"icon":@"home_temperature"},
                             @{@"name":@"呼吸次数", @"icon":@"home_breathe"},
                             @{@"name":@"睡眠", @"icon":@"home_sleep"},
                             @{@"name":@"血压", @"icon":@"home_blood_pressure"},
                             @{@"name":@"血糖", @"icon":@"home_blood_glucose"},
                             @{@"name":@"血氧", @"icon":@"home_blood_o2"},
                             @{@"name":@"静息心率", @"icon":@"home_heart_rate"},
                             @{@"name":@"BMI", @"icon":@"home_bmi"}];
    NSMutableArray *manArr = [NSMutableArray array];
        
    for (int i = 0; i < manImgList.count; i++) {
        
        NSDictionary *img = manImgList[i];

        // NSDictionary *img in manImgList
        QMUIButton *btn = [[QMUIButton alloc] init];
        btn.imagePosition = QMUIButtonImagePositionTop;// 将图片位置改为在文字下方
        btn.tintColorAdjustsTitleAndImage = UIColor.blackColor;
        btn.adjustsImageTintColorAutomatically = NO;
        btn.spacingBetweenImageAndTitle = 10;
        [btn setImage:UIImageMake(img[@"icon"]) forState:UIControlStateNormal];
        [btn setTitle:img[@"name"] forState:UIControlStateNormal];
        btn.titleLabel.font = DYFont(14);
        btn.tag = i;
        [manContent addSubview:btn];
        [btn addTarget:self action:@selector(healthChcekClick:) forControlEvents:UIControlEventTouchUpInside];
        
//         btn.sd_layout
//            .heightIs(53);
        [manArr addObject:btn];
        
        //
//        [btn setupAutoSizeWithHorizontalPadding:10 buttonHeight:10];
    }
    
    // 实现masonry水平固定间隔方法
    [manArr mas_distributeViewsAlongAxis:MASAxisTypeHorizontal withFixedSpacing:10 leadSpacing:0 tailSpacing:0];
    
    // 设置array的垂直方向的约束
    [manArr mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(manContent).mas_offset(0);
    }];
    
    // sd的等间距排列
//    [manContent setupAutoWidthFlowItems:manArr withPerRowItemsCount:30 verticalMargin:15 horizontalMargin:10 verticalEdgeInset:0 horizontalEdgeInset:0];
    
    // 设置scrollview conetsize
    [manContent setupAutoContentSizeWithRightView:manArr.lastObject rightMargin:0];


    // 就医绿色通道
    UIImageView *green = [[UIImageView alloc] initWithImage:IMAGE_NAMED(@"findTeam")];
    green.contentMode = UIViewContentModeScaleAspectFill;
    green.layer.cornerRadius = 10;
    green.layer.masksToBounds = YES;
    green.clipsToBounds = YES;
    green.userInteractionEnabled = YES;
    [scrollView addSubview:green];
    UITapGestureRecognizer *findTeamTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toFindTeamClick)];
    [green addGestureRecognizer:findTeamTap];
    
    green.sd_layout
    .topSpaceToView(healthManage, 15)
    .rightSpaceToView(scrollView, 15)
    .leftSpaceToView(scrollView, 15)
    .heightIs(80);
    
    
    // 健康评估
    HEAssesListView *assList = [[HEAssesListView alloc] init];
    assList.superVC = self;
    _assList = assList;
    [scrollView addSubview:assList];
    
    assList.sd_layout
    .topSpaceToView(green, 15)
    .rightSpaceToView(scrollView, 15)
    .leftSpaceToView(scrollView, 15)
    .heightIs(270);
    
    [assList getTableHeight:^(CGFloat height) {
        assList.sd_layout
        .topSpaceToView(green, 15)
        .rightSpaceToView(scrollView, 15)
        .leftSpaceToView(scrollView, 15)
        .heightIs(height);
        
        [assList updateLayout];
    }];
    
    // 健康资讯
    HEMissonListView *missonList = [[HEMissonListView alloc] init];
    missonList.vc = self;
    _missonList = missonList;
    [scrollView addSubview:missonList];
    
    missonList.sd_layout
    .topSpaceToView(assList, 15)
    .rightSpaceToView(scrollView, 15)
    .leftSpaceToView(scrollView, 15)
    .heightIs(530);
    
    [missonList getTableHeight:^(CGFloat height) {
        missonList.sd_layout
        .topSpaceToView(assList, 15)
        .rightSpaceToView(scrollView, 15)
        .leftSpaceToView(scrollView, 15)
        .heightIs(height);
        
        [missonList updateLayout];
    }];
    
    
    // 健康视频
    HEVideoListView *videoList = [[HEVideoListView alloc] init];
    videoList.vc = self;
    _videoList = videoList;
    [scrollView addSubview:videoList];
    
    videoList.sd_layout
    .topSpaceToView(missonList, 15)
    .rightSpaceToView(scrollView, 15)
    .leftSpaceToView(scrollView, 15)
    .heightIs(530);
    
    [videoList getTableHeight:^(CGFloat height) {
        videoList.sd_layout
        .topSpaceToView(missonList, 15)
        .rightSpaceToView(scrollView, 15)
        .leftSpaceToView(scrollView, 15)
        .heightIs(height);
        
        [videoList updateLayout];
    }];
    
    // 设置scrollview内容竖向自适应
    [scrollView setupAutoContentSizeWithBottomView:videoList bottomMargin:20];
}

- (void)bannerTapClick {
    HEFindDoctorViewController *vc = [HEFindDoctorViewController new];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)itemServerClick:(UIButton *)sender {
    NSInteger  tag = sender.tag;
    
    if (![self toVaildRealUser]) {
        return;
    }
     
    switch (tag) {
        case 0:
        {
            HENurseViewController *vc = [HENurseViewController new];
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case 1:
        {
            HERecoverViewController *vc = [HERecoverViewController new];
//            HECheckPictureViewController *vc = [HECheckPictureViewController new];
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case 2:
        {
            HERecoverViewController *vc = [HERecoverViewController new];
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case 3:
        {
            HEOrgMapViewController *vc = [HEOrgMapViewController new];
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case 4: {
            
            if (!self.drugsUrl) {
                [self loadDrugsUrl];
            }else {
                NSURL * file = [NSURL URLWithString:_drugsUrl];
             
                RootWebViewController *webView = [[RootWebViewController alloc] initWithUrl:file.absoluteString];
                webView.isShowCloseBtn = YES;
                 webView.title = @"医药上门";
                 webView.showPageTitle = NO;
                 webView.header = @{@"Referer":@"https://pay.miaoshou.com"}.mutableCopy;
                [self.navigationController pushViewController:webView animated:YES];
            }
        }
            break;
            
            
        default:
            break;
    }
}

- (void)searchClickhandler {
    self.searchData = [HESearchData new];
    self.searchData.superVC = self;
    [self.searchData toSearchVC];
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    return NO;
}

- (UIView *)targetTransitionView{
    return _nav;
}
- (BOOL)isNeedTransition{
    return YES;
}

- (BOOL)toVaildRealUser {
    if (![[UserManager sharedUserManager] getUserInfo].verifyStatus) {
        HERealNameAuthAlterController *vc = [HERealNameAuthAlterController new];
        [self.view addSubview:vc.view];
        return NO;
     }
    return YES;
}

#pragma mark - laod Data
- (void)loadDrugsUrl {
    [WOAFNetWorkingHandle POSTWithBaseUrl:KServerUrl suffixUrl:KdrugsUrl parameters:@{} success:^(id  _Nonnull responseObject) {
        HEObjectDataResponse *response = [HEObjectDataResponse mj_objectWithKeyValues:responseObject];
        self.drugsUrl = response.data;
        
        if (response.success) {
            NSURL * file = [NSURL URLWithString:self.drugsUrl];
            RootWebViewController *webView = [[RootWebViewController alloc] initWithUrl:file.absoluteString];
            webView.isShowCloseBtn = YES;
             webView.title = @"医药上门";
             webView.showPageTitle = NO;
             webView.header = @{@"Referer":@"https://pay.miaoshou.com"}.mutableCopy;
             
            [self.navigationController pushViewController:webView animated:YES];
        }
    } failure:^(NSError * _Nonnull error) {
    }];
}

- (void)refreshWeatherData {
    [self getCurrentLocal];
}

- (void)setupWetherData {
    NSString *area = nil;
    if ([DYTools isBlankString:self.selectCity]) {
        area = [self.courrentLoc.rgcData.city removeLastStringWith:@"市"];
    }else {
        area = self.selectCity;
    }
    
    if ([DYTools isBlankString:area]) {
        [self.mainScrollView.mj_header endRefreshing];
        return;
    }
    
    [WOAFNetWorkingHandle GETNoHUDWithBaseUrl:KServerUrl suffixUrl:KweatherInfo parameters:@{@"area": IsNotNull(area)} success:^(id  _Nonnull responseObject) {
        HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];
        self.weatherInfo = [HEWeatherModel mj_objectWithKeyValues: response.data];
        
        self.cityLb.text = area;
        self.weatherLb.text = [NSString stringWithFormat:@"%@%@", IsNotNull(self.weatherInfo.weather), IsNotNull(self.weatherInfo.temperature)];
        
        [self.mainScrollView.mj_header endRefreshing];
    } failure:^(NSError * _Nonnull error) {
        [self.mainScrollView.mj_header endRefreshing];
    }];
}

// 单次定位
- (void)getCurrentLocal {
    [self.locationManager requestLocationWithReGeocode:YES withNetworkState:YES completionBlock:^(BMKLocation * _Nullable location, BMKLocationNetworkState state, NSError * _Nullable error) {
        if (error) {
            [self.mainScrollView.mj_header endRefreshing];
            NSLog(@"locError:{%ld - %@};", (long)error.code, error.localizedDescription);
        }
       if (location) {//得到定位信息，添加annotation
           self.courrentLoc = location;
            if (location.location) {
                [UserManager sharedUserManager].currentCoordinate = location.location.coordinate;
            }
            if (location.rgcData) {
                [self setupWetherData];
            }
        }
    }];
}

#pragma mark -
#pragma mark - 获取是否有未读
- (void)getHasRead {
    [WOAFNetWorkingHandle POSTNoHUDWithBaseUrl:KServerUrl suffixUrl:KunReadMsg parameters:@{} success:^(id  _Nonnull responseObject) {
        HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];
        if (response.success) {
            NSNumber *sys_num = (NSNumber *)response.data[@"system_message"];
            NSNumber *ask_num = (NSNumber *)response.data[@"ask_message"];

            NSInteger sysInfoNum = sys_num.integerValue;
            NSInteger askInfoNum = ask_num.integerValue;
            
            UITabBarItem *msgTabbar = self.navigationController.tabBarController.viewControllers[1].tabBarItem;

            if ((sysInfoNum + askInfoNum) > 0) {
                [msgTabbar pp_setBadgeHeight:16];
                [msgTabbar pp_moveBadgeWithX: 3 Y: 5];
                msgTabbar.badgeView.font = DYBlodFont(14);

                msgTabbar.badgeView.qmui_borderPosition = QMUIViewBorderPositionBottom | QMUIViewBorderPositionTop | QMUIViewBorderPositionLeft | QMUIViewBorderPositionRight;
                msgTabbar.badgeView.qmui_borderWidth = 2;
                msgTabbar.badgeView.qmui_borderColor = KWhiteColor;
            }else {

                [msgTabbar pp_hiddenBadge];
            }
        }
    } failure:^(NSError * _Nonnull error) {
    }];
}

#pragma mark - 定位权限

- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    if (status == kCLAuthorizationStatusAuthorizedAlways ||
        status == kCLAuthorizationStatusAuthorizedWhenInUse) {
        [self refreshWeatherData];
    }
}

-(void)requestWhenInUseAuthorization {
    if (![self getUserLocationAuth]) {
         if ([self.sysLocManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
            [self.sysLocManager requestWhenInUseAuthorization];
        }
    }
}
 
- (BOOL)getUserLocationAuth {
    BOOL result = NO;
    switch ([CLLocationManager authorizationStatus]) {
        case kCLAuthorizationStatusNotDetermined: //用户没有选择是否要使用定位服务（弹框没选择，或者根本没有弹框）
            break;
        case kCLAuthorizationStatusRestricted: //定位服务授权状态受限制，可能由于活动限制了定位服务，并且用户不能改变当前的权限，这个状态有可能不是用户拒绝的，但是也有可能是用户拒绝的
            break;
        case kCLAuthorizationStatusDenied: //用户在设置中关闭定位功能，或者用户明确的在弹框之后选择禁止定位
            [Dialog toastBottom:@"请前往设置开启定位权限~"];
            break;
        case kCLAuthorizationStatusAuthorizedAlways:
            result = YES;
            break;
        case kCLAuthorizationStatusAuthorizedWhenInUse:
            result = YES;
            break;
            
        default:
            break;
    }
    return result;
}

- (CLLocationManager *)sysLocManager {
    if (!_sysLocManager) {
        _sysLocManager = [[CLLocationManager alloc] init];
        _sysLocManager.desiredAccuracy = kCLLocationAccuracyBest;
        _sysLocManager.distanceFilter = kCLLocationAccuracyHundredMeters;
        _sysLocManager.delegate = self;
    }
    return _sysLocManager;
}

#pragma mark -
- (void)toFindTeamClick {
    HEFindTeamViewController *vc = [HEFindTeamViewController new];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)healthChcekClick:(UIButton *)sender {
    NSInteger tag = sender.tag;
    HEHealthCheckDataController *vc = [HEHealthCheckDataController new];
    vc.index = tag;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)toHealthMangeClick {
    HEHealthManageViewController *vc = [HEHealthManageViewController new];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)scanClick {
    ZFScanViewController *vc = [ZFScanViewController new];
    [self.navigationController pushViewController:vc animated:YES];
    
    vc.returnScanBarCodeValue = ^(NSString *barCodeString) {
        
    };
}

- (void)selectCityClick {
    JFCSConfiguration *config = [[JFCSConfiguration alloc] init];
    config.hideAreaSwitchButton = YES;
    JFCSTableViewController *vc = [[JFCSTableViewController alloc] initWithConfiguration:config delegate:self];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)serverClick:(UITapGestureRecognizer *)tap {
    NSInteger tag = tap.view.tag;
    if (tag == 1) {
        HEFreeConsulViewController *vc = [HEFreeConsulViewController new];
        [self.navigationController pushViewController:vc animated:YES];
    }else if( tag == 2)  {
        HEFindDoctorViewController *vc = [HEFindDoctorViewController new];
        [self.navigationController pushViewController:vc animated:YES];
    }
}


- (void)loadUserPrivateData {
    __weak typeof(self) weakself = self;
    [WOAFNetWorkingHandle POSTNoHUDWithBaseUrl:KServerUrl suffixUrl:KprivateDocinfo parameters:@{} success:^(id  _Nonnull responseObject) {
        HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];
        if (response.success && response.data != nil) {
            weakself.privateModel = [HEDoctorInfoModel mj_objectWithKeyValues: response.data];
            weakself.isHasPrivate = YES;
            [self loadNewDocInfo];
        }else {
            weakself.isHasPrivate = NO;
            [self hideDocIMView];
        }
    } failure:^(NSError * _Nonnull error) {
    }];
}

- (void)loadNewDocInfo {
    
    HEPageRequest *req = [HEPageRequest new];
    req.pageNum = 1;
    req.pageSize = 1;
    [req addParmas:self.privateModel.user_id key:@"doctor_id"];
    
    [WOAFNetWorkingHandle POSTNoHUDWithBaseUrl:KServerUrl suffixUrl:KImInfo parameters:req success:^(id  _Nonnull responseObject) {
        NSLog(@"response：  %@", [responseObject mj_JSONString]);
 
        HEArrayResponse *response = [HEArrayResponse mj_objectWithKeyValues:responseObject];
        NSArray *msgList = [HEIMInfoEntity mj_objectArrayWithKeyValuesArray:response.data];
        
        if (msgList.count > 0) {
            [self.imInfoView configIMModel:msgList[0] docModel:self.privateModel];;
            [self showDocIMView];
        }else {
            [self hideDocIMView];
        }
        
    } failure:^(NSError * _Nonnull error) {
    }];
}

- (void)showDocIMView {
    [_mainScrollView addSubview:self.imInfoView];
    
    _banner.alpha = 1;
    [UIView animateWithDuration:.3 animations:^{
        _banner.alpha = 0;

        _imInfoView.sd_layout
        .topSpaceToView(_mainScrollView, 5)
        .leftSpaceToView(_mainScrollView, 15)
        .rightSpaceToView(_mainScrollView, 15)
        .heightIs(120);
        
        _serWarp.sd_layout
        .topSpaceToView(_imInfoView, 10)
        .leftSpaceToView(_mainScrollView, 0)
        .rightSpaceToView(_mainScrollView, 0)
        .heightIs(80);

        [_serWarp updateLayout];
    } completion:^(BOOL finished) {
        _banner.hidden = YES;
    }];
}

- (void)hideDocIMView {
     
    [self.imInfoView removeFromSuperview];
    
    _banner.alpha = 0;
    _banner.hidden = NO;

    [UIView animateWithDuration:.3 animations:^{
        _banner.alpha = 1;
        _banner.sd_layout
        .topSpaceToView(_mainScrollView, 5)
        .leftSpaceToView(_mainScrollView, 15)
        .rightSpaceToView(_mainScrollView, 15)
        .heightIs(80);
        
        _serWarp.sd_layout
        .topSpaceToView(_banner, 15)
        .leftSpaceToView(_mainScrollView, 0)
        .rightSpaceToView(_mainScrollView, 0)
        .heightIs(80);

        [_serWarp updateLayout];
    } completion:^(BOOL finished) {
    }];
}

#pragma mark JFCSTableViewControllerDelegate
- (void)viewController:(JFCSTableViewController *)viewController didSelectCity:(JFCSBaseInfoModel *)model {
    self.selectCity = model.name;
    [self setupWetherData];
}

#pragma mark - HESocketManagerDelegate
- (void)onRecvMessages:(HEIMMessageModel *)message {
    if (message.message.modelType == HEIMUserModelTypeIM) {
        [self loadNewDocInfo];
    }
}

#pragma mark - lazyLoad

- (BMKLocationManager *)locationManager {
    if (!_locationManager) {
        //初始化BMKLocationManager类的实例
        _locationManager = [[BMKLocationManager alloc] init];
        //设置定位管理类实例的代理
        _locationManager.delegate = self;
        //设定定位坐标系类型，默认为 BMKLocationCoordinateTypeGCJ02
        _locationManager.coordinateType = BMKLocationCoordinateTypeBMK09LL;
        //设定定位精度，默认为 kCLLocationAccuracyBest
        _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        //设定定位类型，默认为 CLActivityTypeAutomotiveNavigation
        _locationManager.activityType = CLActivityTypeAutomotiveNavigation;
        //指定定位是否会被系统自动暂停，默认为NO
        _locationManager.pausesLocationUpdatesAutomatically = NO;
        /**
         是否允许后台定位，默认为NO。只在iOS 9.0及之后起作用。
         设置为YES的时候必须保证 Background Modes 中的 Location updates 处于选中状态，否则会抛出异常。
         由于iOS系统限制，需要在定位未开始之前或定位停止之后，修改该属性的值才会有效果。
         */
        _locationManager.allowsBackgroundLocationUpdates = NO;
        /**
         指定单次定位超时时间,默认为10s，最小值是2s。注意单次定位请求前设置。
         注意: 单次定位超时时间从确定了定位权限(非kCLAuthorizationStatusNotDetermined状态)
         后开始计算。
         */
        _locationManager.locationTimeout = 10;
    }
    return _locationManager;
}

- (HEDocImInfoView *)imInfoView {
    if (!_imInfoView) {
        _imInfoView = [HEDocImInfoView new];
        _imInfoView.vc = self;
    }
    return _imInfoView;
}
 

@end
